package pl.edu.pb.wi.pwnography.controller;

import java.util.Arrays;
import java.util.logging.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import pl.edu.pb.wi.pwnography.model.ParsedData;
import pl.edu.pb.wi.pwnography.model.form.ColumnForm;
import pl.edu.pb.wi.pwnography.session.FileList;

@Controller
@RequestMapping("/data")
public class DataManagement {
    private static final Logger log = Logger.getLogger(DataManagement.class
	    .getName());

    private static final String SHOW_FILE_DATA_ERROR = "Nie udało się pokazać danych dla pliku %d oraz rewizji %d";

    @Autowired
    private FileList fileList;

    public void setFileList(FileList fileList) {
	this.fileList = fileList;
    }

    @RequestMapping("{fileId}/revision/{revisionId}")
    public String showFileRevisionData(@ModelAttribute("form") ColumnForm form,
	    @PathVariable("fileId") int fileId,
	    @PathVariable("revisionId") int revisionId, Model model) {
	log.info(String.format("Trying to get file %d revision %d data",
		fileId, revisionId));

	try {
	    ParsedData file = fileList.getParsedData(fileId);
	    Integer revision = (revisionId == -1) ? file.getCurrentRevision()
		    : revisionId;

	    if (form == null || form.getColumns().size() == 0) {
		model.addAttribute("form", new ColumnForm());
		model.addAttribute("dataArray", file.getRevisionData(revision)
			.getAsArray());
	    } else {
		model.addAttribute("dataArray", file.getRevisionData(revision)
			.getAsArray(form.getColumns()));
	    }

	    model.addAttribute("fileName", file.getFileName());
	    model.addAttribute("revisionId", revision);
	    model.addAttribute("columnList", file.getColumnNames());

	    return "/file/data";
	} catch (Exception e) {
	    log.info(String
		    .format("Generating data as array for file %d revision %d failed. Exception: %s",
			    fileId, revisionId, e.getMessage()));

	    model.addAttribute("errorMsgs", Arrays.asList(new String[] { String
		    .format(SHOW_FILE_DATA_ERROR, fileId, revisionId) }));
	}

	return "forward:/files/list";
    }
}
